import { Promise } from 'drunk-base';
import { observable, computed } from 'mobx';
import { getAccount, updateAccount, createAccount, getMyAccount, getMediaOptionsByName } from './AccountHttpResource';
import { notEmpty } from '../../../service/Validator';
import { Validate, ItemModel, IItemProps } from '../../ItemModel';
import { currUser } from "../../CurrUserModel";

export interface IAccountModel extends IItemProps {
    login: string;
    password: string;
    contactInfo: string;
    note: string;
    superAdmin: boolean;
    meiti?: { id: string; name: string };
}

export class AccountModel extends ItemModel<IAccountModel> {

    private timerId: number;

    @observable data: IAccountModel = {
        login: "",
        password: "",
        note: "",
        contactInfo: "",
        superAdmin: false,
        meiti: {
            id: "",
            name: "",
        },
    };

    @observable newPassword: string;
    @observable newPasswordConfirm: string;
    @observable mediaOptions: any[];

    @Validate(`请选择一个媒体`)
    @computed get meitiIdValid() {
        // TODO 媒体管理账号只能新增当前媒体旗下账号
        if (!currUser.superAdmin) {
            return true;
        }
        return this.data && this.data.superAdmin || notEmpty(this.data.meiti.id)
    }

    @Validate("请输入用户名称")
    @computed get loginValid() { return this.data && notEmpty(this.data.login) }

    @Validate(`请输入合法的密码`)
    @computed get passwordValid() { return this.data && notEmpty(this.data.password) && this.data.password.length >= 6 }

    @Validate(`请输入联系方式`)
    @computed get contactInfoValid() { return this.data && notEmpty(this.data.contactInfo) }

    @Validate(`请输入备注信息`)
    @computed get noteValid() { return this.data && notEmpty(this.data.note) }

    @computed get newPasswordValid() { return notEmpty(this.newPassword) && this.newPassword.length >= 6 }
    @computed get newPasswordConfirmValid() { return notEmpty(this.newPasswordConfirm) && this.newPassword === this.newPasswordConfirm }

    fetchMyAccountData() {
        return getMyAccount().then(res => {
            this.data = res;
            this.id = res.id;
        });
    }

    createItemImpl(data: IAccountModel) {
        return createAccount(data);
    }

    fetchItemImpl(id: string) {
        return getAccount(id);
    }

    updateItemImpl(id: string, data: IAccountModel) {
        return updateAccount(id, data);
    }

    fetchEventOptions(name: string) {
        clearTimeout(this.timerId);

        this.timerId = setTimeout(() => {
            getMediaOptionsByName(name).then(res => {
                this.mediaOptions = res;
            });
        }, 300);
    }

    updateMediaOptions(id: string) {
        let [options] = this.mediaOptions.filter(options => id === options.id);
        this.data.meiti.id = options.id;
        this.data.meiti.name = options.name;
    }

    updateAccount() {
        let result = this.validateNewPassword();
        if (!result.success) {
            return Promise.reject(result);
        }

        let validateResult = this.validateExcept("passwordValid", "loginValid", "meitiIdValid");
        if (!validateResult.success) {
            return Promise.reject(validateResult);
        }

        let data = { contactInfo: this.data.contactInfo, note: this.data.note, password: this.newPassword };

        this.isSubmiting = true;
        return updateAccount(this.id, data).then(
            res => {
                this.isSubmiting = false;
                this.id = res.id;
                this.data = { ...this.data, ...res };
                return { success: true, message: "提交成功", data: res }
            },
            e => {
                this.isSubmiting = false;
                return Promise.reject({ success: false, message: `提交失败，${e.res.message}` });
            }
        );
    }

    validateNewPassword() {
        let success = false;
        let message = "";

        if (!this.newPasswordValid) {
            message = `请输入新密码`;
        }
        else if (!this.newPasswordConfirmValid) {
            message = `两次输入的密码不一致`;
        }
        else {
            success = true;
        }

        return { success, message };
    }
}